import 'package:date_format/date_format.dart';
import 'package:decimal/decimal.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/cache/id_cache.dart';
import 'package:wu_you/data/repository/trad_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/trad_model.dart';
import 'package:wu_you/page/dialog/input_dialog.dart';
import 'package:wu_you/page/trad/page_publish.dart';
import 'package:wu_you/page/trad/page_trad_order.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/trad_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/dialog_general.dart';
import 'package:wu_you/widgets/http_status_widget.dart';

///交易广告区
class TradingMainPage extends StatefulWidget{
  final TradTypeModel model;
  TradingMainPage({Key key,this.model}):super(key: key);
  @override
  TradingMainPageState createState() => TradingMainPageState();
}
class TradingMainPageState extends State<TradingMainPage>{
  List<String> _tabs = [];

  @override
  void initState() {
    super.initState();
  }
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    _tabs.clear();
    _tabs = ['${message['trad20']}','${message['trad21']}'];
    return DefaultTabController(
      length: _tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text("${widget.model.name}"),
        ),
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Container(
              height: 58,
              color: Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Container(
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(Utils.getImgPath('ic_trad_publish'),width: 26,height: 26,),
                        SizedBox(width: 6,),
                        Text("${message['trad7']}",style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),)
                      ],
                    ),
                    padding: EdgeInsets.only(left: 12,right: 12,top: 6,bottom: 6),
                  ).addGesture(() {
                    NavigatorUtil.navigateToPage(context, PublishPage(wid: widget.model.id,));
                  }),
                  SizedBox(
                    width: 1,
                    height: 15,
                    child: DecoratedBox(
                      decoration: BoxDecoration(color: Colors.grey),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 12,right: 12,top: 6,bottom: 6),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(Utils.getImgPath('ic_trad_order'),width: 26,height: 26,),
                        SizedBox(width: 6,),
                        Text("${message['trad8']}",style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),)
                      ],
                    ),
                  ).addGesture(() {
                    NavigatorUtil.navigateToPage(context, TradOrderPage(name: widget.model.name,));
                  })
                ],
              ),
            ),
            Divider(thickness: 5,color: HexColor("#F6F6F6"),),
            Container(
              width: double.infinity,
              color: Colors.white,
              padding: EdgeInsets.only(left: 10,right: 10),
              child: TabBar(
                labelColor: AppColors.primaryColor,
                indicatorColor: AppColors.primaryColor,
                unselectedLabelColor: AppColors.textHintColor,
                indicatorSize: TabBarIndicatorSize.label,
                isScrollable: true,
                unselectedLabelStyle: TextStyle(fontSize: 16),
                labelStyle: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
                indicatorPadding: EdgeInsets.all(5),
                tabs: _tabs.map((String c){
                  return Tab(
                    text: c,
                  );
                }).toList(),
              ),
            ),
            Divider(),

            Expanded(
              child: TabBarView(
                // index: controller.index,
                  physics: NeverScrollableScrollPhysics(), //禁止滑动
                  children: [
                    _TypeNumView(wid: widget.model.id,type: 2,),
                    _TypeNumView(wid: widget.model.id,type: 1,)
                  ]
              ),
              // IndexedStack(
              //   index: controller.index,
              //   // physics: NeverScrollableScrollPhysics(), //禁止滑动
              //   children: _tabs.map((e) => _buildTypeNumView(e)).toList(),
              // ),
            )
          ],
        ),
      )
    );
  }

}

class _TypeNumView extends StatefulWidget{
  final String wid;
  final int type;
  _TypeNumView({Key key,this.wid,this.type}):super(key: key);
  @override
  _TypeNumViewState createState() => _TypeNumViewState();
}
class _TypeNumViewState extends State<_TypeNumView>{

  TextStyle style = TextStyle(fontSize: 14,color: AppColors.textHintColor);

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Padding(
      padding: EdgeInsets.only(left: 6,right: 6,top: 12,bottom: 12),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(child: Container(child: Text("${message['trad9']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad10']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad11']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad12']}",style: style,),alignment: Alignment.center,)),
            ],
          ),
          Expanded(
            child:HttpWidget<TradOrders, TradOrdersBloc>(
              create: (context) => TradOrdersBloc()..add(TradOrdersEvent(wid: widget.wid,size: widget.type)),
              child: (context, data) {
                return Column(
                  children: [
                    Column(
                      children: _sellList(data.sell),
                    ),
                    Column(
                      children: _buyList(data.buy),
                    )
                  ],
                );
              }
            )
          )
        ],
      ),
    );
  }

  List<Widget> _sellList(List<TradOrderItem> list){
    double width = MediaQuery.of(context).size.width;
    List<Widget> viewList = [];
    Widget child;
    if(list == null){
      return viewList;
    }
    for(int i = 0;i < list.length;i++){
      child = Row(
        children: [
          Expanded(child: Container(child: Text("${message['trad13']}${i + 1}",style: TextStyle(color: AppColors.primaryColor,fontSize: 15),),alignment: Alignment.center,)),
          Expanded(child: Container(child: Text("${Decimal.parse(list[i].price).toString()}",style: TextStyle(color: AppColors.primaryColor,fontSize: 15),),alignment: Alignment.center,)),
          Expanded(child: Container(child: Text("${double.parse(list[i].total_quantity).toInt()}",style: TextStyle(color: AppColors.primaryColor,fontSize: 15),),alignment: Alignment.center,)),

          Expanded(
              child: Container(
                child: Text("${message['trad14']}",style: TextStyle(color: AppColors.secondColor),),
                alignment: Alignment.center,
              ).addGesture(() {
                showModalBottomSheet(
                    context: context,
                    isScrollControlled: true,
                    backgroundColor: Colors.transparent,
                    builder: (ctx) {
                      return DialogGeneral(
                        title: "",
                        minHeight: width * 1.2,
                        padding: EdgeInsets.zero,
                        child: ListExpansionView(size: widget.type.toString(),wid: widget.wid,price: list[i].price,type: "1",),
                      );
                    });
              })
          )
        ],
      ).addPadding(EdgeInsets.only(top: 8));
      viewList.add(child);
    }
    return viewList;
  }

  List<Widget> _buyList(List<TradOrderItem> list){
    double width = MediaQuery.of(context).size.width;
    List<Widget> viewList = [];
    Widget child;
    if(list == null){
      return viewList;
    }
    for(int i = 0;i < list.length;i++){
      child = Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(child: Container(child:  Text("${message['trad15']}${i + 1}",style: TextStyle(color: Colors.green,fontSize: 15),),alignment: Alignment.center,)),
          Expanded(child: Container(child:  Text("${Decimal.parse(list[i].price).toString()}",style: TextStyle(color: Colors.green,fontSize: 15),),alignment: Alignment.center,)),
          Expanded(child: Container(child:  Text("${double.parse(list[i].total_quantity).toInt()}",style: TextStyle(color: Colors.green,fontSize: 15),),alignment: Alignment.center,)),
          Expanded(
              child: Container(
                child: Text("${message['trad14']}",style: TextStyle(color: AppColors.secondColor),),
                alignment: Alignment.center,
              ).addGesture(() {
                showModalBottomSheet(
                    context: context,
                    isScrollControlled: true,
                    backgroundColor: Colors.transparent,
                    builder: (ctx) {
                      return DialogGeneral(
                        title: "",
                        minHeight: width * 1.2,
                        padding: EdgeInsets.zero,
                        child: ListExpansionView(size: widget.type.toString(),wid: widget.wid,price: list[i].price,type: "2",),
                      );
                    });
              })
          ),
        ],
      ).addPadding(EdgeInsets.only(top: 8));
      viewList.add(child);
    }
    return viewList;
  }
}



///展开列表
class ListExpansionView extends StatefulWidget {
  final String size;
  final String wid;
  final String price;
  final String type;
  ListExpansionView({
    Key key,
    this.size,
    this.wid,
    this.price,
    this.type
  }) : super(key: key);

  @override
  ListExpansionViewState createState() => ListExpansionViewState();
}

class ListExpansionViewState extends State<ListExpansionView> {
  TextStyle style = TextStyle(fontSize: 14,color: AppColors.textHintColor);

  BuildContext ctx;
  var message;

  var future;
  @override
  void initState() {
    super.initState();
    future = UserPhoneCache().get();
  }

  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          Row(
            children: [
              Expanded(child: Container(child: Text("${message['trad9']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad10']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad11']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad17']}",style: style,),alignment: Alignment.center,)),
              Expanded(child: Container(child: Text("${message['trad12']}",style: style,),alignment: Alignment.center,)),
            ],
          ),
          Expanded(
            child: HttpWidget<List<TradOrderExp>, TradOrderExpBloc>(
            create: (context) => TradOrderExpBloc()..add(TradOrderExpEvent(size: widget.size,wid: widget.wid,price: widget.price,type: widget.type)),
              child: (context, data) {
                ctx = context;
                return ListView.builder(
                  padding: EdgeInsets.only(bottom: 12),
                  itemBuilder: (context,index){
                    TradOrderExp item = data[index];
                    return Row(
                      children: [
                        Expanded(child: Container(child: Text("${item.type == "1" ? "${message['trad13']}${index+1}" : "${message['trad15']}${index+1}"}",style: TextStyle(color: item.type == "1" ? AppColors.primaryColor:Colors.green,fontSize: 15),),alignment: Alignment.center,)),
                        Expanded(child: Container(child: Text("${Decimal.parse(item.price).toString()}",style: TextStyle(color: item.type == "1" ? AppColors.primaryColor:Colors.green,fontSize: 15),),alignment: Alignment.center,)),
                        Expanded(child: Container(child: Text("${double.parse(item.total_quantity).toInt()}",style: TextStyle(color: item.type == "1" ? AppColors.primaryColor:Colors.green,fontSize: 15),),alignment: Alignment.center,)),
                        Expanded(
                          child: Container(
                            child: Wrap(
                              // mainAxisSize: MainAxisSize.min,
                              children: _paymentImage(item.payment),
                            ),
                            alignment: Alignment.center,
                          )
                        ),
                        Expanded(
                          child: FutureBuilder(
                            future: future,
                            builder: (context,data){
                              String phone = data.data;
                              if(phone != null && phone != ''){
                                return Container(
                                  child: Text("${item.type == "1" ? "${message['trad18']}" : "${message['trad19']}"}",style: TextStyle(color: AppColors.secondColor),),
                                  alignment: Alignment.center,
                                ).addGesture(() {
                                  showCupertinoDialog(
                                    context: context,
                                    builder: (context) {
                                      return CupertinoAlertDialog(
                                        title: Text('${message['trad24']}'),
                                        content: Text(item.type == "1" ? '${message['trad22']}': '${message['trad23']}'),
                                        actions: <Widget>[
                                          CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                                            Navigator.pop(context);
                                          },),
                                          CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                                            LoadingApi.func(TradRepository().tradGoodAdd(item.id, item.type), context,complete: (v){
                                              ToastUtils.show("$v", context);
                                              Navigator.pop(context);
                                              BlocProvider.of<TradOrderExpBloc>(ctx).add(TradOrderExpEvent(size: widget.size,wid: widget.wid,price: widget.price,type: widget.type));
                                            },error: (e){
                                              ToastUtils.show("$e", context);
                                              Navigator.pop(context);
                                            });
                                          },),
                                        ],
                                      );
                                    });
                                  });
                              }else{
                                return Container(
                                  child: Text("${item.type == "1" ? "${message['trad18']}" : "${message['trad19']}"}",style: TextStyle(color: AppColors.secondColor),),
                                  alignment: Alignment.center,
                                ).addGesture(() {
                                  if(item.type == "1"){
                                    showDialog(
                                      context: context,
                                      builder: (context) => InputDialog(),
                                    ).then((value){
                                      future = UserPhoneCache().get();
                                      setState(() {});
                                    });
                                  }else{
                                    showCupertinoDialog(
                                    context: context,
                                    builder: (context) {
                                      return CupertinoAlertDialog(
                                        title: Text('${message['trad24']}'),
                                        content: Text(item.type == "1" ? '${message['trad22']}': '${message['trad23']}'),
                                        actions: <Widget>[
                                          CupertinoDialogAction(child: Text('${message['address14']}'),onPressed: (){
                                            Navigator.pop(context);
                                          },),
                                          CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                                            LoadingApi.func(TradRepository().tradGoodAdd(item.id, item.type), context,complete: (v){
                                              ToastUtils.show("$v", context);
                                              Navigator.pop(context);
                                              BlocProvider.of<TradOrderExpBloc>(ctx).add(TradOrderExpEvent(size: widget.size,wid: widget.wid,price: widget.price,type: widget.type));
                                            },error: (e){
                                              ToastUtils.show("$e", context);
                                              Navigator.pop(context);
                                            });
                                          },),
                                        ],
                                      );
                                    });
                                  }
                                });
                              }
                            },
                          )
                        )
                      ],
                    ).addPadding(EdgeInsets.only(top: 10));
                  },
                  itemCount: data.length,
                );
              },emptyBuilder: (context){
                ctx = context;
                return Container();
              },
            )
          )
        ],
      ).addPadding(EdgeInsets.only(top: 8,left: 12,right: 12))
    );
  }

  List<Widget> _paymentImage(String payment){
    List<Widget> viewList = [];
    if(payment.contains(',')){
       List<String> list = payment.split(',');
       for(int i = 0;i < list.length;i++){
         if(list[i] == "1"){
           viewList.add(Image.asset(Utils.getImgPath('payment_one'),width: 17,height: 17,fit: BoxFit.fill,));
         }else if(list[i] == "2"){
           viewList.add(Image.asset(Utils.getImgPath('payment_two'),width: 17,height: 17,fit: BoxFit.fill,));
         }else if(list[i] == "3"){
           viewList.add(Image.asset(Utils.getImgPath('payment_three'),width: 17,height: 17,fit: BoxFit.fill,));
         }else if(list[i] == "4"){
           viewList.add(Image.asset(Utils.getImgPath('payment_four'),width: 17,height: 17,fit: BoxFit.fill,));
         }else if(list[i] == "5"){
           viewList.add(Image.asset(Utils.getImgPath('payment_five'),width: 17,height: 17,fit: BoxFit.fill,));
         }
       }
    }else{
       if(payment == "1"){
         viewList.add(Image.asset(Utils.getImgPath('payment_one'),width: 18,height: 18,fit: BoxFit.fill,));
       }else if(payment == "2"){
         viewList.add(Image.asset(Utils.getImgPath('payment_two'),width: 18,height: 18,fit: BoxFit.fill,));
       }else if(payment == "3"){
         viewList.add(Image.asset(Utils.getImgPath('payment_three'),width: 18,height: 18,fit: BoxFit.fill,));
       }else if(payment == "4"){
         viewList.add(Image.asset(Utils.getImgPath('payment_four'),width: 18,height: 18,fit: BoxFit.fill,));
       }else if(payment == "5"){
         viewList.add(Image.asset(Utils.getImgPath('payment_five'),width: 18,height: 18,fit: BoxFit.fill,));
       }
    }
    return viewList;
  }
}